import axios from "axios";
import { storageLocal } from "/@/utils/storage";
import NotifMessage from "/@/utils/message/notification";
import router from "/@/router/index";
import { ElNotification } from "element-plus";

// interface fileType {
//   fileName: string;
//   fileSize: number;
//   fileType: string;
//   uuidFile: string;
// }

// interface pdfFileType {
//   contractInfoId: string;
//   flowId: string;
//   instanceId: string;
// }

const baseUrl = import.meta.env.VITE_BASE_URL;

export const getUrl = async (uuidFile: string): Promise<string> => {
  let downloadUrl = `/rdms-admin/open/download`;

  if (import.meta.env.MODE === "production") {
    downloadUrl = `${baseUrl}/rdms-admin/open/download`;
  }

  return downloadUrl + "?uuidFile=" + uuidFile;
};

export const download = (fileInfo): void => {
  if (!fileInfo) return;
  let authorization = "";

  if (storageLocal.getItem("rdms-info")) {
    authorization = storageLocal.getItem("rdms-info")?.accessToken;
  }
  let downloadUrl = `/rdms-admin/common/file/download`;

  if (import.meta.env.MODE === "production") {
    downloadUrl = `${baseUrl}/rdms-admin/common/file/download`;
  }

  console.log(import.meta.env.MODE, "mode", downloadUrl);

  const formData = { uuidFile: fileInfo?.uuidFile };
  axios({
    method: "get",
    url: downloadUrl,
    params: formData,
    responseType: "blob",
    headers: {
      Authorization: authorization
    }
  })
    .then(res => {
      const data = res.data;
      // @ts-ignore
      const url = window.URL.createObjectURL(new Blob([data]));
      const a = document.createElement("a");
      a.style.display = "none";
      a.href = url;
      // a.setAttribute("download", `${fileInfo.uuidFile}${fileInfo.fileType}`);
      a.setAttribute("download", `${fileInfo.fileName}`);
      document.body.appendChild(a);
      a.click();
      window.URL.revokeObjectURL(a.href);
      document.body.removeChild(a);
    })
    .catch(err => {
      if (err.response) {
        if (err.response.status === 500) {
          NotifMessage.error("您没有该操作权限");
        } else if (err?.response?.status === 403) {
          NotifMessage.error("登录失效，请重新登录");
          router.replace("/login");
        }
      } else if (err.request) {
        console.log(err.request);
      } else {
        console.log("err", err.message);
      }
    });
};

export const viewpdf = (fileInfo: any, type: string): void => {
  if (!fileInfo) return;
  let authorization = "";
  if (storageLocal.getItem("rdms-info")) {
    authorization = storageLocal.getItem("rdms-info")?.accessToken;
  }

  let downloadUrl = "";
  if (type === "arrival") {
    downloadUrl = "/rdms-admin/arrivedAcceptance/downloadAcc";
  } else if (type === "common") {
    downloadUrl = `/rdms-admin/flowForm/downloadAcc/${fileInfo.contractInfoId}`;
  } else if (type === "quality") {
    downloadUrl = `/rdms-admin/qtyCheck/downloadQty/${fileInfo.contractInfoId}`;
  }

  if (import.meta.env.MODE === "production") {
    downloadUrl = `${baseUrl}${downloadUrl}`;
  }

  const formData = fileInfo;
  axios({
    method: "post",
    url: downloadUrl,
    data: formData,
    responseType: "blob",
    headers: {
      Authorization: authorization
    }
  })
    .then(res => {
      const data = res.data;
      // @ts-ignore
      const url = window.URL.createObjectURL(new Blob([data]));
      const fileUrl = encodeURIComponent(url);
      // console.log(window, "window", fileUrl);
      window.open(
        `${window.location.origin}${
          import.meta.env.VITE_PUBLIC_PATH
        }pdfjs/web/viewer.html?file=${fileUrl}`,
        "_blank"
      );
    })
    .catch(err => {
      if (err.response) {
        if (err.response.status === 500) {
          NotifMessage.error("您没有该操作权限");
        } else if (err?.response?.status === 403) {
          NotifMessage.error("登录失效，请重新登录");
          router.replace("/login");
        }
      } else if (err.request) {
        console.log(err.request);
      } else {
        console.log("err", err.message);
      }
    });
};

/**
 *
 * @param fileInfo
 * @param type
 */
export const downloadpdf = (fileInfo: any, type: string): void => {
  if (!fileInfo) return;
  let authorization = "";
  if (storageLocal.getItem("rdms-info")) {
    authorization = storageLocal.getItem("rdms-info")?.accessToken;
  }
  let downloadUrl = "";

  if (type === "arrival") {
    downloadUrl = "/rdms-admin/arrivedAcceptance/downloadAcc";
  } else if (type === "common") {
    downloadUrl = `/rdms-admin/flowForm/downloadAcc/${fileInfo.contractInfoId}`;
  } else if (type === "quality") {
    downloadUrl = `/rdms-admin/qtyCheck/downloadQty/${fileInfo.contractInfoId}`;
  }

  if (import.meta.env.MODE === "production") {
    downloadUrl = `${baseUrl}${downloadUrl}`;
  }

  const formData = {
    contractInfoId: fileInfo.contractInfoId,
    flowId: fileInfo.flowId,
    instanceId: fileInfo.instanceId
  };
  axios({
    method: "post",
    url: downloadUrl,
    data: formData,
    responseType: "blob",
    headers: {
      Authorization: authorization
    }
  })
    .then(res => {
      const data = res.data;
      // @ts-ignore
      const url = window.URL.createObjectURL(new Blob([data]));
      const a = document.createElement("a");
      a.style.display = "none";
      a.href = url;
      // a.setAttribute("download", `${fileInfo.uuidFile}${fileInfo.fileType}`);
      a.setAttribute("download", `${fileInfo.pdfName}.pdf`);
      document.body.appendChild(a);
      a.click();
      window.URL.revokeObjectURL(a.href);
      document.body.removeChild(a);
    })
    .catch(err => {
      if (err.response) {
        if (err.response.status === 500) {
          NotifMessage.error("您没有该操作权限");
        } else if (err?.response?.status === 403) {
          NotifMessage.error("登录失效，请重新登录");
          router.replace("/login");
        }
      } else if (err.request) {
        console.log(err.request);
      } else {
        console.log("err", err.message);
      }
    });
};

export const downloadXml = (fileInfo): void => {
  if (!fileInfo) return;
  let authorization = "";
  if (storageLocal.getItem("rdms-info")) {
    authorization = storageLocal.getItem("rdms-info")?.accessToken;
  }
  let downloadUrl = `/rdms-admin/flowProjectProgress/export/xml`;

  if (import.meta.env.MODE === "production") {
    downloadUrl = `${baseUrl}/rdms-admin/flowProjectProgress/export/xml`;
  }

  const formData = {
    ganttJsonStr: fileInfo.ganttJsonStr,
    fileName: fileInfo.fileName
  };

  axios({
    method: "post",
    url: downloadUrl,
    data: formData,
    responseType: "blob",
    headers: {
      Authorization: authorization
    }
  })
    .then(res => {
      const data = res.data;
      // @ts-ignore
      const url = window.URL.createObjectURL(new Blob([data]));
      const a = document.createElement("a");
      a.style.display = "none";
      a.href = url;
      // a.setAttribute("download", `${fileInfo.uuidFile}${fileInfo.fileType}`);
      a.setAttribute("download", `${fileInfo.fileName}`);
      document.body.appendChild(a);
      a.click();
      window.URL.revokeObjectURL(a.href);
      document.body.removeChild(a);
    })
    .catch(err => {
      if (err.response) {
        if (err.response.status === 500) {
          NotifMessage.error("您没有该操作权限");
        } else if (err?.response?.status === 403) {
          NotifMessage.error("登录失效，请重新登录");
          router.replace("/login");
        }
      } else if (err.request) {
        console.log(err.request);
      } else {
        console.log("err", err.message);
      }
    });
};

export const postDocumentDownload = (fileInfo): void => {
  if (!fileInfo) return;
  let authorization = "";
  if (storageLocal.getItem("rdms-info")) {
    authorization = storageLocal.getItem("rdms-info")?.accessToken;
  }
  let downloadUrl = `/rdms-admin/sysDocument/docZipDowload`;

  if (import.meta.env.MODE === "production") {
    downloadUrl = `${baseUrl}/rdms-admin/sysDocument/docZipDowload`;
  }

  const formData = {
    zipDownloadDTOList: fileInfo
  };
  axios({
    method: "post",
    url: downloadUrl,
    data: formData,
    responseType: "blob",
    headers: {
      Authorization: authorization
    }
  })
    .then(res => {
      const data = res.data;
      let filename = res.headers; //下载后文件名
      filename = filename["content-disposition"];
      filename =
        filename?.split(";")[1]?.split("filename=")[1] ??
        `${new Date().getTime()}.zip`;

      // @ts-ignore
      const url = window.URL.createObjectURL(new Blob([data]));
      const a = document.createElement("a");
      a.style.display = "none";
      a.href = url;
      // a.setAttribute("download", `${fileInfo.uuidFile}${fileInfo.fileType}`);
      a.setAttribute("download", `${filename}`);
      document.body.appendChild(a);
      a.click();
      window.URL.revokeObjectURL(a.href);
      document.body.removeChild(a);
    })
    .catch(err => {
      if (err.response) {
        if (err.response.status === 500) {
          const reader: any = new FileReader(); // 创建读取文件对象
          reader.readAsText(err.response.data, "utf-8"); // 设置读取的数据以及返回的数据类型为utf-8
          reader.addEventListener("loadend", () => {
            const res = JSON.parse(reader.result); // 返回的数据
            ElNotification.error({
              message: res.message,
              title: "ERROR",
              offset: 60,
              duration: 2000
            });
            // NotifMessage.error(res.message);
            // console.log(res, "返回结果"); // { name: "小花" }
          });
        } else if (err?.response?.status === 403) {
          NotifMessage.error("登录失效，请重新登录");
          router.replace("/login");
        }
      } else if (err.request) {
        console.log(err.request);
      } else {
        console.log("err", err.message);
      }
    });
};

export const postScientificDownload = (params): void => {
  if (!params) return;
  let authorization = "";
  if (storageLocal.getItem("rdms-info")) {
    authorization = storageLocal.getItem("rdms-info")?.accessToken;
  }
  let downloadUrl = `/rdms-admin/scientific/achievements/export`;

  if (import.meta.env.MODE === "pre") {
    downloadUrl = `${baseUrl}/rdms-admin/scientific/achievements/export`;
  }

  const formData = {
    ...params
  };
  axios({
    method: "post",
    url: downloadUrl,
    data: formData,
    responseType: "blob",
    headers: {
      Authorization: authorization
    }
  })
    .then(res => {
      const data = res.data;
      let filename = res.headers; //下载后文件名
      filename = filename["content-disposition"];
      filename = `科研成果${new Date().getTime()}.xlsx`;

      // @ts-ignore
      const url = window.URL.createObjectURL(new Blob([data]));
      const a = document.createElement("a");
      a.style.display = "none";
      a.href = url;
      // a.setAttribute("download", `${fileInfo.uuidFile}${fileInfo.fileType}`);
      a.setAttribute("download", `${filename}`);
      document.body.appendChild(a);
      a.click();
      window.URL.revokeObjectURL(a.href);
      document.body.removeChild(a);
    })
    .catch(err => {
      if (err.response) {
        if (err.response.status === 500) {
          const reader: any = new FileReader(); // 创建读取文件对象
          reader.readAsText(err.response.data, "utf-8"); // 设置读取的数据以及返回的数据类型为utf-8
          reader.addEventListener("loadend", () => {
            const res = JSON.parse(reader.result); // 返回的数据
            ElNotification.error({
              message: res.message,
              title: "ERROR",
              offset: 60,
              duration: 2000
            });
            // NotifMessage.error(res.message);
            // console.log(res, "返回结果"); // { name: "小花" }
          });
        } else if (err?.response?.status === 403) {
          NotifMessage.error("登录失效，请重新登录");
          router.replace("/login");
        }
      } else if (err.request) {
        console.log(err.request);
      } else {
        console.log("err", err.message);
      }
    });
};

export const postDownload = (downloadUrl, fileName, data = {}): any => {
  let authorization = "";
  if (storageLocal.getItem("rdms-info")) {
    authorization = storageLocal.getItem("rdms-info")?.accessToken;
  }

  return axios({
    method: "post",
    url: downloadUrl,
    responseType: "blob",
    data: data,
    headers: {
      Authorization: authorization
    }
  })
    .then(res => {
      const data = res.data;
      let filename = res.headers; //下载后文件名
      filename = filename["content-disposition"];
      filename = fileName;

      // @ts-ignore
      const url = window.URL.createObjectURL(new Blob([data]));
      const a = document.createElement("a");
      a.style.display = "none";
      a.href = url;
      // a.setAttribute("download", `${fileInfo.uuidFile}${fileInfo.fileType}`);
      a.setAttribute("download", `${filename}`);
      document.body.appendChild(a);
      a.click();
      window.URL.revokeObjectURL(a.href);
      document.body.removeChild(a);
    })
    .catch(err => {
      if (err.response) {
        if (err.response.status === 500) {
          const reader: any = new FileReader(); // 创建读取文件对象
          reader.readAsText(err.response.data, "utf-8"); // 设置读取的数据以及返回的数据类型为utf-8
          reader.addEventListener("loadend", () => {
            const res = JSON.parse(reader.result); // 返回的数据
            ElNotification.error({
              message: res.message,
              title: "ERROR",
              offset: 60,
              duration: 2000
            });
            // NotifMessage.error(res.message);
            // console.log(res, "返回结果"); // { name: "小花" }
          });
        } else if (err?.response?.status === 403) {
          NotifMessage.error("登录失效，请重新登录");
          router.replace("/login");
        }
      } else if (err.request) {
        console.log(err.request);
      } else {
        console.log("err", err.message);
      }
    });
};
